// #ifndef VUE3
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
			// #endif

			// #ifdef VUE3
			import {
				createStore
			} from 'vuex'
			const store = createStore({
				// #endif
				state: {
					userInfo: {},
					access_token: undefined,
					currentLocation: {},
					selectLocation: {},
					hasLogin: false,
					isUniverifyLogin: false,
					loginProvider: "",
					openid: null,
					testvuex: false,
					colorIndex: 0,
					colorList: ['#FF0000', '#00FF00', '#0000FF'],
					noMatchLeftWindow: true,
					active: 'componentPage',
					leftWinActive: '/pages/component/view/view',
					activeOpen: '',
					menu: [],
					univerifyErrorMsg: '',
					// vuex测试例使用
					username: "foo",
					sex: "男",
					age: 10
				},
				mutations: {
					clearLoginInfo(state) {
						state.access_token = undefined;
						state.userInfo = {};
						state.hasLogin = false;
						// 只清除必要的存储项，避免影响其他数据
						try {
							uni.removeStorageSync('access_token');
							uni.removeStorageSync('token_expire_time');
							uni.removeStorageSync('user_info');
						} catch (e) {
							console.error('清除登录信息失败', e);
						}
					},
					setAccessToken(state, val) {
						state.access_token = val;
						// 存储token和过期时间
						const expireTime = Date.now() + 2 * 60 * 60 * 1000; // 2小时的毫秒数
						try {
							uni.setStorageSync('access_token', val);
							uni.setStorageSync('token_expire_time', expireTime);
						} catch (e) {
							console.error('存储token失败', e);
						}
					},
					setCurrentLocation(state, val) {
						console.log('val--------', val);
						state.currentLocation = val;
						try {
							uni.setStorageSync('current_location', JSON.stringify(val));
						} catch (e) {
							console.error('存储当前位置失败', e);
						}
					},
					setSelectLocation(state, val) {
						state.selectLocation = val;
						try {
							uni.setStorageSync('select_location', JSON.stringify(val));
						} catch (e) {
							console.error('存储选择位置失败', e);
						}
					},
					setUserInfo(state, val) {
						// 先打印传入的 val 确保数据正确
						// console.log('setUserInfo 接收到的数据', val);

						// 确保 val 是对象类型
						if (!val || typeof val !== 'object') {
							console.error('setUserInfo: 无效的用户数据', val);
							return;
						}
						// 统一 sex 字段为数字类型
						const normalizedData = {
							...val,
							sex: typeof val.sex === 'string' ? {
								'男': 0,
								'女': 1,
								'未知': 2
							} [val.sex] ?? 2 : val.sex
						};
						state.userInfo = {
							...state.userInfo, // 保留原有数据
							...val // 用新数据覆盖
						};

						try {
							uni.setStorageSync('user_info', JSON.stringify(state.userInfo));
							// console.log('本地存储更新成功');
						} catch (e) {
							console.error('setUserInfo: 本地存储更新失败', e);
						}
						// console.log('更新后的 state.userInfo:', state.userInfo);
					},
					login(state, provider) {
						state.hasLogin = true;
						state.loginProvider = provider || 'unknown';
					},
					logout(state) {
						state.hasLogin = false;
						state.openid = null;
						state.access_token = undefined;
						state.userInfo = {};
					},
					setOpenid(state, openid) {
						state.openid = openid;
					},
					setTestTrue(state) {
						state.testvuex = true;
					},
					setTestFalse(state) {
						state.testvuex = false;
					},
					setColorIndex(state, index) {
						state.colorIndex = index;
					},
					setMatchLeftWindow(state, matchLeftWindow) {
						state.noMatchLeftWindow = !matchLeftWindow;
					},
					setActive(state, tabPage) {
						state.active = tabPage;
					},
					setLeftWinActive(state, leftWinActive) {
						state.leftWinActive = leftWinActive;
					},
					setActiveOpen(state, activeOpen) {
						state.activeOpen = activeOpen;
					},
					setMenu(state, menu) {
						state.menu = menu;
					},
					setUniverifyLogin(state, payload) {
						state.isUniverifyLogin = !!payload;
					},
					setUniverifyErrorMsg(state, payload = '') {
						state.univerifyErrorMsg = payload;
					},
					// vuex测试例使用
					increment(state) {
						state.age++;
					},
					incrementTen(state, payload) {
						state.age += payload.amount;
					},
					resetAge(state) {
						state.age = 10;
					}
				},
				getters: {
					currentColor(state) {
						return state.colorList[state.colorIndex];
					},
					// vuex测试例使用
					doubleAge(state) {
						return state.age * 2;
					}
				},
				actions: {
					// 初始化登录状态 - 优化版本
					initLoginState({
						commit
					}) {
						return new Promise((resolve) => {
							try {
								const token = uni.getStorageSync('access_token');
								const userInfo = uni.getStorageSync('user_info');
								const expireTime = uni.getStorageSync('token_expire_time');

								// 如果没有token或用户信息，直接返回未登录
								if (!token || !userInfo) {
									commit('clearLoginInfo');
									resolve(false);
									return;
								}

								// 检查token是否过期
								if (expireTime && expireTime < Date.now()) {
									commit('clearLoginInfo');
									resolve(false);
									return;
								}

								// 解析用户信息
								let parsedUserInfo;
								try {
									parsedUserInfo = typeof userInfo === 'string' ? JSON.parse(
										userInfo) : userInfo;
								} catch (e) {
									console.error('解析用户信息失败:', e);
									commit('clearLoginInfo');
									resolve(false);
									return;
								}

								// 设置登录状态
								commit('setAccessToken', token);
								commit('setUserInfo', parsedUserInfo);
								commit('login');
								resolve(true);
							} catch (e) {
								console.error('初始化登录状态异常:', e);
								commit('clearLoginInfo');
								resolve(false);
							}
						});
					},

					// 初始化应用状态 - 优化版本
					async initializeApp({
						dispatch,
						state
					}) {
						try {
							// 如果已登录，直接返回
							if (state.hasLogin && state.access_token) {
								return true;
							}
							// 初始化登录状态，但不跳转
							const isLoggedIn = await dispatch('initLoginState');
							return isLoggedIn; // 仅返回登录状态，由首页判断是否跳转
						} catch (error) {
							console.error('初始化应用状态失败:', error);
							store.commit('clearLoginInfo');
							return false; // 错误时也不强制跳转，由首页处理
						}
					},

					// vuex测试例使用
					incrementAsync(context, payload) {
						context.commit('incrementTen', payload);
					},

					// lazy loading openid
					getUserOpenId: async function({
						commit,
						state
					}) {
						return await new Promise((resolve, reject) => {
							if (state.openid) {
								resolve(state.openid);
							} else {
								uni.login({
									success: (data) => {
										commit('login');
										setTimeout(function() { //模拟异步请求服务器获取 openid
											const openid = '123456789';
											console.log(
												'uni.request mock openid[' +
												openid + ']');
											commit('setOpenid', openid);
											resolve(openid);
										}, 1000);
									},
									fail: (err) => {
										console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务',
											err);
										reject(err);
									}
								});
							}
						});
					},

					getPhoneNumber: function({
						commit
					}, univerifyInfo) {
						return new Promise((resolve, reject) => {
							uni.request({
								url: 'https://97fca9f2-41f6-449f-a35e-3f135d4c3875.bspapp.com/http/univerify-login',
								method: 'POST',
								data: univerifyInfo,
								success: (res) => {
									const data = res.data;
									if (data.success) {
										resolve(data.phoneNumber);
									} else {
										reject(res);
									}
								},
								fail: (err) => {
									reject(err);
								}
							});
						});
					}
				}
			});

			export default store;